import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Table, Card, PaginationProps } from '@arco-design/web-react';
import SearchForm from './form';
import { isEmpty } from 'lodash-es';
import { getColumns } from './constants';
import { querySubBanks } from '@/services/merchant';

export function BankSelect({ onSelect }: { onSelect: (record: any) => void }) {
  const tableCallback = useCallback(
    (record: Record<string, any>) => {
      onSelect && onSelect(record);
    },
    [onSelect]
  );

  const columns = useMemo(() => getColumns(tableCallback), [tableCallback]);

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  useEffect(() => {
    if (!isEmpty(formParams)) {
      fetchData();
    }
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    querySubBanks({
      pageNo: current,
      pageSize,
      ...formParams,
    }).then((res) => {
      setData(res.data.list);
      setPatination({
        ...pagination,
        current,
        pageSize,
        total: res.data.totalCount,
      });
      setLoading(false);
    });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }

  return (
    <Card>
      <SearchForm onSearch={handleSearch} />
      <Table
        rowKey="subBankCode"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />
    </Card>
  );
}
